//src/controller/user.js

const Base = require('./base.js');
module.exports = class extends Base {


  async indexAction(){

    let model = this.model('user');
    let data = await model.limit(10).select();
    //data returns [{name: 'thinkjs', email: 'admin@thinkjs.org'}, ...]
    const userSession=await this.session('userinfo');
    console.log(userSession.openid);
    this.assign('data',data);
    return this.display(); //渲染模板
  }

  async showAction(){
    let id=this.get('id') || 1;
    let model = this.model('user');
    let data = await model.where({id: id}).find();
    //data returns [{name: 'thinkjs', email: 'admin@thinkjs.org'}, ...]
    console.log(data);
    this.assign('info',data);
    return this.display(); //渲染模板
  }

  async storeAction(){
    let insertId='';
    if(this.isPost)
    {
      let field=this.post('name,mobile,type,address');
      let model = this.model('user');
      insertId = await model.add(field);
    }
    console.log(this.isPost);
    this.assign({title:'新增用户信息','inserId':insertId});

    return this.display(); //渲染模板
  }

  async updateAction(){

    let field=this.post('name,mobile,type,address,id');
    let model = this.model('user');
    let affectedRows  = await model.where({id:field.id}).update(field);
    console.log(affectedRows);
    this.redirect('/user/show/'+field.id);
  }

  __call(){
    this.body = '__call';
  }

  /**
   * 删除分类
   */
  async delAction() {
    let model = this.model("user");
    let id = this.post('id');
    let delNums = model.where({id: ['IN', id]}).delete();
    if(delNums){
      this.json({"succ":true});
    }else{
      this.json({"succ":false});
    }
  }
}